package com.muqi.app.qlearn.ui;

import java.util.HashMap;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.easeui.widget.EaseAlertDialog;
import com.muqi.app.im.db.InviteMessgeDao;
import com.muqi.app.im.db.UserDao;
import com.muqi.app.im.qmain.Constant;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.im.ui.ChatActivity;
import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;

import com.muqi.app.qlearn.modles.PersonBean;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.MoneyPayActivity;
import com.muqi.app.user.widget.CircularImageView;
import com.muqi.app.user.widget.TwoItemsWindow;
import com.muqi.app.user.widget.TwoItemsWindow.PopWindowListener;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class UserHomepagerActivity extends BaseFragmentActivity implements
		OnClickListener, PopWindowListener {
	public static final String IM_OR_MOBILE_OR_USERID = "im_or_mobile_or_userid";
	private CircularImageView userAvtar;
	private TextView userName;
	private TextView userInfos;
	private TextView userSex;
	private TextView userClass;
	private LinearLayout userButton;
	private TextView userBtnText;

	private PersonBean personInfo = null;
	private boolean isMyFriends = false;

	private TwoItemsWindow window;
	private String get_im_or_userid;
	private boolean isFriend = false;
	private boolean isConcern = false;
	private ImageView iv_more;
	private TextView userFollwer;
	private LinearLayout userLlClass;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_user_homepager);
	}

	@Override
	protected void onInit() {
		userAvtar = (CircularImageView) findViewById(R.id.mine_avatar);
		userAvtar.setBorderWidth(3);
		userName = (TextView) findViewById(R.id.mine_name);
		userInfos = (TextView) findViewById(R.id.mine_info);
		userSex = (TextView) findViewById(R.id.user_sex);
		userClass = (TextView) findViewById(R.id.user_class);
		userButton = (LinearLayout) findViewById(R.id.user_button);
		userBtnText = (TextView) findViewById(R.id.user_button_text);
		iv_more = (ImageView) findViewById(R.id.iv_more);
		userFollwer = (TextView) findViewById(R.id.mine_follwer);
		userLlClass = (LinearLayout) findViewById(R.id.mine_class);

	}

	@Override
	protected void onData() {
		get_im_or_userid = getIntent().getStringExtra(IM_OR_MOBILE_OR_USERID);
		if (get_im_or_userid == null || TextUtils.isEmpty(get_im_or_userid)) {
			finish();
			return;
		}
		loadinguserbaseinfos(get_im_or_userid);
	}

	private void loadinguserbaseinfos(String im_or_userid) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("str", im_or_userid);
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			sendMap.put("type", "follow");
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_USER_BASEINFOS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						personInfo = ResponseUtils.getUserBaseInfos(mContext,
								result);
						if (personInfo != null) {
							showUserInfosView();
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void showUserInfosView() {
		GlideImageUtils.setAvatar(this, personInfo.avatarInfo.fileurl_02,
				userAvtar);
		userName.setText(personInfo.name);
		if ("parents".equals(personInfo.user_type)) {
			userInfos.setText("家长");
			userLlClass.setVisibility(View.GONE);
			userFollwer.setVisibility(View.GONE);
		} else if ("student".equals(personInfo.user_type)) {
			userInfos.setText("学生");
			userFollwer.setVisibility(View.GONE);
		} else if ("teacher".equals(personInfo.user_type)) {
			userInfos.setText("老师");
		} else if ("classteacher".equals(personInfo.user_type)) {
			userInfos.setText("班主任");
		} else if ("headmaster".equals(personInfo.user_type)) {
			userInfos.setText("校长");
		}
		if(personInfo.school_info!=null && personInfo.school_info.size()>0&& personInfo.school_info.get(0) != null){
			userClass.setText(personInfo.school_info.get(0).school_name
					+ personInfo.school_info.get(0).class_name);
		}
	
		userFollwer.setText(personInfo.flower_count+"");

		if ("1".equals(personInfo.concern)) {
			isConcern = true;
			initFriendsView("取消关注");
		} else {
			isConcern = false;
			initFriendsView("关注");
		}
		if (personInfo.sex.equals("female")) {
			userSex.setText("女");
		} else {
			userSex.setText("男");
		}
		if (personInfo.im_user_id != null
				&& !TextUtils.isEmpty(personInfo.im_user_id)) {
			if (EMChatManager.getInstance().getCurrentUser()
					.equals(personInfo.im_user_id)) {

			} else if (EMHelper.getInstance().getContactList()
					.containsKey(personInfo.im_user_id)) {
				userButton.setVisibility(View.VISIBLE);
				userButton.setOnClickListener(this);
				userBtnText.setText("发消息");
				isMyFriends = true;
			} else {
				userButton.setVisibility(View.VISIBLE);
				userButton.setOnClickListener(this);
				userBtnText.setText("加为好友");
			}
		}
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_button:
			if (isMyFriends) {
				if (ChatActivity.activityInstance != null) {
					finish();
				} else {
					// 进入聊天页面
					Intent intent = new Intent(this, ChatActivity.class);
					intent.putExtra(Constant.EXTRA_USER_ID,
							personInfo.im_user_id);
					startActivity(intent);
				}
			} else {
				addContact(personInfo.im_user_id);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 添加contact
	 * 
	 * @param view
	 */
	public void addContact(final String toAddUsername) {
		if (EMChatManager.getInstance().getCurrentUser().equals(toAddUsername)) {
			new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
					.setTitleText("不能添加自己").setConfirmText("确定")
					.showCancelButton(false)
					.setConfirmClickListener(new OnSweetClickListener() {
						@Override
						public void onClick(SweetAlertDialog mDialog) {
							mDialog.dismissWithAnimation();
						}
					}).show();
			return;
		}
		if (EMHelper.getInstance().getContactList().containsKey(toAddUsername)) {
			// 提示已在好友列表中(在黑名单列表里)，无需添加
			if (EMContactManager.getInstance().getBlackListUsernames()
					.contains(toAddUsername)) {
				new EaseAlertDialog(this, "黑名单好友，无需添加").show();
				return;
			}
			new EaseAlertDialog(this, R.string.This_user_is_already_your_friend)
					.show();
			return;
		}
		new Thread(new Runnable() {
			public void run() {
				try {
					// demo写死了个reason，实际应该让用户手动填入
					EMContactManager.getInstance().addContact(toAddUsername,
							"加个好友呗");
					runOnUiThread(new Runnable() {
						public void run() {
							ShowToast.showShort(UserHomepagerActivity.this,
									"好友申请已发送成功");
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {

						}
					});
				}
			}
		}).start();
	}

	/**
	 * 删除联系人
	 * 
	 * @param toDeleteUser
	 */
	public void deleteContact(final String tobeDeleteUser) {
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setMessage("正在删除...");
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		new Thread(new Runnable() {
			public void run() {
				try {
					EMContactManager.getInstance()
							.deleteContact(tobeDeleteUser);
					InviteMessgeDao invitedao = new InviteMessgeDao(
							UserHomepagerActivity.this);
					invitedao.deleteMessage(tobeDeleteUser);
					// 删除db和内存中此用户的数据
					UserDao userdao = new UserDao(UserHomepagerActivity.this);
					userdao.deleteContact(tobeDeleteUser);
					EMHelper.getInstance().getContactList()
							.remove(tobeDeleteUser);
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							UserHomepagerActivity.this.finish();
							if (ChatActivity.activityInstance != null)
								ChatActivity.activityInstance.finish();
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							ShowToast.showShort(UserHomepagerActivity.this,
									e.getMessage());
						}
					});
				}
			}
		}).start();
	}

	public void more(View v) {
		if (window != null) {
			window.showPopupWindow(v);
		}

	}

	/**
	 * 关注该学生
	 */
	private void followPerson(String id, final String action) {
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("id", id);
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("action", action);
		sendMap.put("token", mSpUtil.getToken());
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.MY_CONCERN_ACTION_API, sendMap);
		MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				if (resuleCode == RESULTCODE.SUCCESS) {
					if("no".equals(action)){
						showToast("取消关注");
					}else if("yes".equals(action)){
						showToast("关注成功");
					}
					
					loadinguserbaseinfos(get_im_or_userid);
					Intent intent = new Intent(
							MoneyPayActivity.PAY_WITH_SUCCESS);
					sendBroadcast(intent);
				}
			}
		});

	}

	private void initFriendsView(String follow) {
		if (!EMChatManager.getInstance().getCurrentUser()
				.equals(get_im_or_userid)) {// first not myself
			iv_more.setVisibility(View.VISIBLE);
			if (EMHelper.getInstance().getContactList()
					.containsKey(get_im_or_userid)) {// third is friend?
				isFriend = true;
				window = new TwoItemsWindow(this, "删除好友", follow, this);
			} else {
				isFriend = false;
				window = new TwoItemsWindow(this, "加为好友", follow, this);
			}

		} else {
			iv_more.setVisibility(View.GONE);
		}
	}

	@Override
	public void onItemsClik(int position) {
		switch (position) {
		case 1:
			if (isFriend) {
				deleteContact(get_im_or_userid);
			} else {
				addContact(get_im_or_userid);
			}
			break;
		case 2:
			if (isConcern) {
				followPerson(personInfo.id, "no");
			} else {
				followPerson(personInfo.id, "yes");
			}

			break;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}
}
